package cn.harry.cabinet.repository

import android.app.Application
import cn.harry.cabinet.database.AppDatabase
import cn.harry.cabinet.model.entity.UsageRecord
import cn.harry.cabinet.model.enums.OperationType
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 * 使用记录数据仓库
 */
class UsageRecordRepository(application: Application) : BaseRepository() {
    
    private val usageRecordDao = AppDatabase.getDatabase(application).usageRecordDao()
    
    /**
     * 插入使用记录
     */
    suspend fun insert(record: UsageRecord): Long = withContext(Dispatchers.IO) {
        usageRecordDao.insertUsageRecord(record)
    }
    
    /**
     * 更新使用记录
     */
    suspend fun update(record: UsageRecord) = withContext(Dispatchers.IO) {
        usageRecordDao.updateUsageRecord(record)
    }
    
    /**
     * 删除使用记录
     */
    suspend fun delete(record: UsageRecord) = withContext(Dispatchers.IO) {
        usageRecordDao.deleteUsageRecord(record)
    }
    
    /**
     * 删除所有使用记录
     */
    suspend fun deleteAll() = withContext(Dispatchers.IO) {
        usageRecordDao.deleteAllUsageRecords()
    }
    
    /**
     * 获取所有使用记录
     */
    suspend fun getAll(): List<UsageRecord> = withContext(Dispatchers.IO) {
        usageRecordDao.getAllUsageRecords()
    }
    
    /**
     * 根据ID获取使用记录
     */
    suspend fun getById(id: Long): UsageRecord? = withContext(Dispatchers.IO) {
        usageRecordDao.getUsageRecordById(id)
    }
    
    /**
     * 根据状态获取使用记录
     */
    suspend fun getByStatus(status: OperationType): List<UsageRecord> = withContext(Dispatchers.IO) {
        usageRecordDao.getUsageRecordsByStatus(status)
    }
    
    /**
     * 根据卡号获取未归还的记录
     */
    suspend fun getUnreturnedRecordByCardNumber(cardNumber: String): UsageRecord? = withContext(Dispatchers.IO) {
        usageRecordDao.getUnreturnedRecordByCardNumber(cardNumber, OperationType.RETRIEVE)
    }
    
    /**
     * 综合查询使用记录
     */
    suspend fun searchRecords(
        employeeId: String? = null,
        name: String? = null,
        cardNumber: String? = null,
        status: OperationType? = null,
        startTime: Long? = null,
        endTime: Long? = null
    ): List<UsageRecord> = withContext(Dispatchers.IO) {
        var records = usageRecordDao.getAllUsageRecords()
        
        // 按条件过滤
        employeeId?.let { id ->
            records = records.filter { it.employeeId.contains(id, ignoreCase = true) }
        }
        
        name?.let { n ->
            records = records.filter { it.name.contains(n, ignoreCase = true) }
        }
        
        cardNumber?.let { card ->
            records = records.filter { it.cardNumber?.contains(card, ignoreCase = true) == true }
        }
        
        status?.let { s ->
            records = records.filter { it.status == s }
        }
        
        // 时间范围过滤
        if (startTime != null || endTime != null) {
            records = records.filter { record ->
                val recordTime = when (record.status) {
                    OperationType.STORE -> record.returnTime?.time
                    OperationType.RETRIEVE -> record.takeTime?.time
                    else -> null
                }
                
                recordTime?.let { time ->
                    val afterStart = startTime?.let { time >= it } ?: true
                    val beforeEnd = endTime?.let { time <= it } ?: true
                    afterStart && beforeEnd
                } ?: false
            }
        }
        
        // 按时间倒序排序
        records.sortedByDescending { 
            (it.returnTime?.time ?: it.takeTime?.time ?: 0)
        }
    }
    
    /**
     * 获取记录总数
     */
    suspend fun getCount(): Int = withContext(Dispatchers.IO) {
        usageRecordDao.getAllUsageRecords().size
    }
}
